"use client";
import React, { useState, useEffect } from "react";
import type { MenuProps } from "antd";
import { Menu, Skeleton, Alert, Empty } from "antd";
import Image from "next/image";
import { useCategories } from "@/hooks/useCategories";
import { useRouter } from "next/navigation";

import { userCenterGet2 } from "@/apis";

interface CenterProductModel {
  productId?: number;
  productName?: string;
  brand?: string;
  model?: string;
  mainPhotoes?: Array<{
    category: string | null;
    attachmentName: string;
    attachmentAddress: string;
  }>;
  gradeName?: string;
  grade?: string;
  coreTarget?: string;
  inspectionStatus?: number;
}

interface HotRecProps {
  product?: CenterProductModel;
}

export default function HotRec({}: HotRecProps) {
  const router = useRouter();
  const [current, setCurrent] = useState("热门");
  const [imgErrorMap, setImgErrorMap] = useState<Record<string, boolean>>({});
  const {
    categories,
    loading: categoryLoading,
    error: categoryError,
  } = useCategories();

  const [productList, setProductList] = useState<CenterProductModel[]>([]);
  const [productLoading, setProductLoading] = useState(false);
  const [productError, setProductError] = useState<string | null>(null);

  const hotCategory = { key: "热门", label: "热门" };
  const menuItems: MenuProps["items"] = [
    hotCategory,
    ...(categories || []).map((category) => ({
      key: category.key,
      label: category.label,
    })),
  ];

  const onClick: MenuProps["onClick"] = (e) => {
    setCurrent(e.key);
  };

  const getFullImageUrl = (relativePath: string) => {
    if (!relativePath) return "/images/default-product.png";
    if (relativePath.startsWith("http")) return relativePath;
    const ossBaseUrl = "https://oss.tz-group.com/";
    const cleanPath = relativePath.startsWith("/")
      ? relativePath.slice(1)
      : relativePath;
    return `${ossBaseUrl}${cleanPath}`;
  };

  const handleImageError = (productId: string | number) => {
    setImgErrorMap((prev) => ({ ...prev, [productId]: true }));
  };

  const fetchProducts = async (categoryKey: string) => {
    setProductLoading(true);
    setProductError(null);
    try {
      const apiCategory = categoryKey.startsWith("sub-")
        ? categoryKey.split("-").slice(2).join("-")
        : categoryKey;
      const params = {
        page: 1,
        size: 9,
        isPopular: categoryKey === "热门" ? true : false,
        keyword: "",
        category: categoryKey === "热门" ? "" : apiCategory,
      };
      const queryString = new URLSearchParams(params).toString();
      const response = await userCenterGet2({
        url: `/user_center/product?${queryString}`,
        baseURL: "/api/proxy",
      });
      setProductList(response?.data?.data?.data || []);
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (err) {
      setProductError("网络异常，无法加载产品数据");
    } finally {
      setProductLoading(false);
    }
  };

  useEffect(() => {
    if (!categoryLoading && !categoryError) {
      fetchProducts(current);
    }
  }, [current, categoryLoading, categoryError]);

  const renderProductCard = (product: CenterProductModel) => {
    const productId = product.productId?.toString() || "unknown";
    const productImg = product.mainPhotoes?.[0]?.attachmentAddress;

    const fullImageUrl = getFullImageUrl(productImg || "");
    const hasError = imgErrorMap[productId];
    const currentGrade = product.grade || "A";
    const allGrades = [
      { grade: "A", label: "A", color: "#027F3F" },
      { grade: "B", label: "B", color: "#68D300" },
      { grade: "C", label: "C", color: "#FFB422" },
      { grade: "D", label: "D", color: "#FF8738" },
    ];

    return (
      <div
        key={productId}
        className="bg-white shadow-md p-4 flex cursor-pointer hover:shadow-lg"
        onClick={() => {
          router.push(`/products/${productId}`);
        }}
      >
        <div className="relative w-[180px] h-[180px] flex-shrink-0">
          <Image
            src={hasError ? "/images/default-product.png" : fullImageUrl}
            alt={product.productName || "产品图片"}
            width={180}
            height={180}
            className="object-cover w-[180px] h-[180px] rounded-lg"
            onError={() => handleImageError(productId)}
          />
        </div>
        <div className="text-sm flex-1 ml-4">
          <h2 className="flex justify-between">
            <div className="text-lg font-bold  text-[#2F2F2F] line-clamp-2 ">
              {product.productName || "未命名产品"}{" "}
            </div>
            <div className="text-[#2CD39C] p-1 border border-[#33D598] bg-[#F2FFF4]">
              {product.coreTarget}
            </div>
          </h2>
          <p className="text-[#091423] mb-1">
            品牌：{product.brand || "未知品牌"}
          </p>
          <p className="text-[#091423] mb-1">
            产地：{product.model || "无规格"}
          </p>
          <p className="text-[#095CDC] mb-2">
            {product.gradeName || "等级认证"}
          </p>
          <div className="flex space-x-2 mt-3">
            {allGrades.map((gradeInfo) => (
              <span
                key={gradeInfo.grade}
                className={`px-3 py-1 text-white rounded transform skew-x-22 text-lg font-medium transition-all duration-200 ${
                  currentGrade === gradeInfo.grade
                    ? "h-8 scale-110 shadow-md"
                    : "h-6 opacity-80"
                }`}
                style={{
                  backgroundColor: gradeInfo.color,
                  lineHeight:
                    currentGrade === gradeInfo.grade ? "24px" : "18px",
                }}
              >
                <span className="transform -skew-x-22 inline-block">
                  {gradeInfo.label}
                </span>
              </span>
            ))}
          </div>
        </div>
      </div>
    );
  };

  const renderProducts = () => {
    if (productLoading) {
      return Array(6)
        .fill(0)
        .map((_, idx) => (
          <div key={idx} className="bg-white shadow-md p-4 flex">
            <Skeleton.Image
              style={{ width: 140, height: 140 }}
              className="mr-6"
            />
            <div className="flex-1 space-y-2">
              <Skeleton active paragraph={{ rows: 1, width: "80%" }} />
              <Skeleton active paragraph={{ rows: 2, width: "100%" }} />
              <Skeleton active paragraph={{ rows: 1, width: "60%" }} />
              <div className="flex space-x-1 mt-2">
                <Skeleton active className="h-6 w-16 rounded" />
              </div>
            </div>
          </div>
        ));
    }

    if (productError) {
      return (
        <div className="col-span-full flex justify-center items-center py-10">
          <Alert message={productError} type="error" showIcon />
        </div>
      );
    }

    if (productList.length === 0) {
      return (
        <div className="col-span-full flex justify-center items-center py-10">
          <Empty description="暂无相关产品" />
        </div>
      );
    }

    return productList.map(renderProductCard);
  };

  return (
    <section>
      <div className="container mx-auto mt-2 flex flex-col items-center justify-between h-full">
        <div className="w-full flex items-center justify-between my-2">
          <div className="flex flex-row items-center justify-start space-x-2">
            <Image
              src="/images/hotIcon.png"
              alt="热门图标"
              width={50}
              height={10}
              className="object-contain"
              style={{ width: "3rem", height: "auto" }}
            />
            {categoryLoading ? (
              <Skeleton active paragraph={{ rows: 1, width: "200px" }} />
            ) : categoryError ? (
              <Alert
                message={categoryError}
                type="error"
                showIcon
                style={{ width: "auto" }}
              />
            ) : (
              <Menu
                onClick={onClick}
                selectedKeys={[current]}
                mode="horizontal"
                items={menuItems}
                className="flex-shrink-0"
              />
            )}
          </div>
          <span
            className="text-sm flex items-center text-[#2570FF] cursor-pointer hover:underline"
            onClick={() => {
              // 直接跳转到/products页面，不带任何参数
              router.push("/products");
            }}
          >
            更多&gt;&gt;
          </span>
        </div>
        <div className="w-full grid gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-3">
          {renderProducts()}
        </div>
      </div>
    </section>
  );
}
